package com.monitor.ui;

import com.monitor.security.RegistrationManager;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.geom.RoundRectangle2D;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;

/**
 * 软件注册对话框，用于显示注册表单和处理注册逻辑
 */
public class RegistrationDialog extends JDialog {
    private static final long serialVersionUID = 1L;
    private RegistrationManager registrationManager;
    private JTextField registrationCodeField;
    private JTextField deptNameField;
    private JTextField emailField;
    private JTextField phoneField;
    private JComboBox<String> securityQuestionCombo;
    private JTextField securityAnswerField;
    private JTextField confirmAnswerField;
    
    private boolean registrationSuccess = false;
    
    /**
     * 创建注册对话框
     * @param parent 父窗口
     * @param registrationManager 注册管理器
     */
    public RegistrationDialog(Frame parent, RegistrationManager registrationManager) {
        super(parent, "软件注册", true);
        this.registrationManager = registrationManager;
        initUI();
    }
    
    private void initUI() {
        setSize(500, 550);
        setLocationRelativeTo(getOwner());
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        
        // 设置窗口为圆角
        addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override
            public void componentResized(java.awt.event.ComponentEvent e) {
                setShape(new java.awt.geom.RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 15, 15));
            }
        });
        
        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        
        // 顶部说明文本
        RoundedPanel topPanel = new RoundedPanel(10);
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
        topPanel.setBackground(new Color(245, 245, 245));
        JLabel infoLabel = new JLabel("为了更好的为您服务,以下信息请您认真填写,有效联系方式或可形式写多个,以此为依据提供多个服务。");
        infoLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        topPanel.add(infoLabel);
        topPanel.add(Box.createVerticalStrut(10));
        
        // 注册表单面板
        JPanel formPanel = createFormPanel();
        
        // 底部按钮面板
        RoundedPanel buttonPanel = new RoundedPanel(new FlowLayout(FlowLayout.CENTER), 10);
        buttonPanel.setBackground(new Color(240, 240, 240));
        JButton submitButton = new JButton("提交");
        JButton cancelButton = new JButton("关闭");
        
        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateForm()) {
                    registerSoftware();
                }
            }
        });
        
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        
        buttonPanel.add(submitButton);
        buttonPanel.add(cancelButton);
        
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    private JPanel createFormPanel() {
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);
        
        // 注册信息部分
        JPanel registrationPanel = new JPanel(new GridBagLayout());
        registrationPanel.setBorder(BorderFactory.createCompoundBorder(
            new RoundedBorder(Color.LIGHT_GRAY, 10),
            BorderFactory.createTitledBorder("注册信息")
        ));
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.weightx = 0.2;
        registrationPanel.add(new JLabel("注册码:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        registrationCodeField = new JTextField();
        registrationPanel.add(registrationCodeField, gbc);
        
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        JLabel requiredLabel1 = new JLabel("*");
        requiredLabel1.setForeground(Color.RED);
        registrationPanel.add(requiredLabel1, gbc);
        
        // 单位信息部分
        JPanel companyPanel = new JPanel(new GridBagLayout());
        companyPanel.setBorder(BorderFactory.createCompoundBorder(
            new RoundedBorder(Color.LIGHT_GRAY, 10),
            BorderFactory.createTitledBorder("产品使用单位(请使用全称)")
        ));
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.2;
        companyPanel.add(new JLabel("单位:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        deptNameField = new JTextField();
        deptNameField.setText("(如: 郑州市金水区第二中学、郑州高新区文化活动中心)");
        deptNameField.setForeground(Color.GRAY);
        companyPanel.add(deptNameField, gbc);
        
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        JLabel requiredLabel3 = new JLabel("*");
        requiredLabel3.setForeground(Color.RED);
        companyPanel.add(requiredLabel3, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.2;
        companyPanel.add(new JLabel("年级:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        JPanel gradePanel = new JPanel(new GridLayout(1, 2, 5, 0));
        JSpinner startGradeSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 12, 1));
        JSpinner endGradeSpinner = new JSpinner(new SpinnerNumberModel(6, 1, 12, 1));
        gradePanel.add(startGradeSpinner);
        gradePanel.add(endGradeSpinner);
        companyPanel.add(gradePanel, gbc);
        
        // 联系方式部分
        JPanel contactPanel = new JPanel(new GridBagLayout());
        contactPanel.setBorder(BorderFactory.createCompoundBorder(
            new RoundedBorder(Color.LIGHT_GRAY, 10),
            BorderFactory.createTitledBorder("联系方式")
        ));
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.2;
        contactPanel.add(new JLabel("邮箱:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        emailField = new JTextField();
        contactPanel.add(emailField, gbc);
        
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        JLabel requiredLabel4 = new JLabel("*");
        requiredLabel4.setForeground(Color.RED);
        contactPanel.add(requiredLabel4, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.2;
        contactPanel.add(new JLabel("电话:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        phoneField = new JTextField();
        contactPanel.add(phoneField, gbc);
        
        // 密码问题部分
        JPanel securityPanel = new JPanel(new GridBagLayout());
        securityPanel.setBorder(BorderFactory.createCompoundBorder(
            new RoundedBorder(Color.LIGHT_GRAY, 10),
            BorderFactory.createTitledBorder("密码问题")
        ));
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.2;
        securityPanel.add(new JLabel("问题:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        List<String> questions = new ArrayList<>();
        questions.add("我喜欢的一个地方?");
        questions.add("我最喜欢的颜色?");
        questions.add("我的生日?");
        questions.add("我最喜欢的食物?");
        securityQuestionCombo = new JComboBox<>(questions.toArray(new String[0]));
        securityPanel.add(securityQuestionCombo, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.2;
        securityPanel.add(new JLabel("答案:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        securityAnswerField = new JTextField();
        securityPanel.add(securityAnswerField, gbc);
        
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        JLabel requiredLabel5 = new JLabel("*");
        requiredLabel5.setForeground(Color.RED);
        securityPanel.add(requiredLabel5, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.2;
        securityPanel.add(new JLabel("确认:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 0.8;
        confirmAnswerField = new JTextField();
        securityPanel.add(confirmAnswerField, gbc);
        
        gbc.gridx = 2;
        gbc.weightx = 0.0;
        JLabel requiredLabel6 = new JLabel("*");
        requiredLabel6.setForeground(Color.RED);
        securityPanel.add(requiredLabel6, gbc);
        
        // 将所有面板添加到主表单面板
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.weightx = 1.0;
        formPanel.add(registrationPanel, gbc);
        
        gbc.gridy = 1;
        formPanel.add(companyPanel, gbc);
        
        gbc.gridy = 2;
        formPanel.add(contactPanel, gbc);
        
        gbc.gridy = 3;
        formPanel.add(securityPanel, gbc);
        
        return formPanel;
    }
    
    private boolean validateForm() {
        // 验证注册码
        if (registrationCodeField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入注册码", "验证失败", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        
        // 验证单位名称
        String deptName = deptNameField.getText().trim();
        if (deptName.isEmpty() || deptName.equals("(如: 郑州市金水区第二中学、郑州高新区文化活动中心)")) {
            JOptionPane.showMessageDialog(this, "请输入单位名称", "验证失败", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        // 验证邮箱
        if (emailField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入邮箱地址", "验证失败", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        // 验证安全问题答案
        if (securityAnswerField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入安全问题答案", "验证失败", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        // 验证确认答案
        if (confirmAnswerField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请确认安全问题答案", "验证失败", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        // 验证两次答案是否一致
        if (!securityAnswerField.getText().equals(confirmAnswerField.getText())) {
            JOptionPane.showMessageDialog(this, "两次输入的安全问题答案不一致", "验证失败", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        return true;
    }
    
    private void registerSoftware() {
        String registrationCode = registrationCodeField.getText().trim();
        String deptName = deptNameField.getText().trim();
        String email = emailField.getText().trim();
        String phone = phoneField.getText().trim();
        String securityQuestion = (String) securityQuestionCombo.getSelectedItem();
        String securityAnswer = securityAnswerField.getText().trim();
        
        // 显示注册进度对话框
        JDialog progressDialog = createProgressDialog("正在连接服务器进行注册，请稍候...");
        
        // 使用SwingWorker在后台线程中执行注册操作
        SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
            @Override
            protected Boolean doInBackground() throws Exception {
                // 执行注册操作 - 使用默认设备类型null
                return registrationManager.register(registrationCode, deptName, email, 
                                                  phone, securityQuestion, securityAnswer, null);
            }
            
            @Override
            protected void done() {
                // 关闭进度对话框
                progressDialog.dispose();
                
                try {
                    boolean success = get();
                    if (success) {
                        // 显示注册成功信息，包括设备ID
                        String deviceId = registrationManager.getDeviceId();
                        String successMsg = "注册成功！\n";
                        if (deviceId != null && !deviceId.isEmpty()) {
                            successMsg += "设备ID: " + deviceId;
                        }
                        
                        JOptionPane.showMessageDialog(RegistrationDialog.this, 
                                                  successMsg, "注册成功", 
                                                  JOptionPane.INFORMATION_MESSAGE);
                        registrationSuccess = true;
                        dispose();
                    } else {
                        // 注册失败的消息已在RegistrationManager中显示
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(RegistrationDialog.this, 
                                              "注册过程中发生错误: " + e.getMessage(), 
                                              "注册错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        
        // 启动后台任务
        worker.execute();
    }
    
    /**
     * 创建进度对话框
     * 
     * @param message 显示的消息
     * @return 进度对话框
     */
    private JDialog createProgressDialog(String message) {
        JDialog dialog = new JDialog(this, "处理中", false);
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        JLabel msgLabel = new JLabel(message);
        msgLabel.setHorizontalAlignment(JLabel.CENTER);
        
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        
        panel.add(msgLabel, BorderLayout.NORTH);
        panel.add(progressBar, BorderLayout.CENTER);
        
        dialog.setContentPane(panel);
        dialog.setSize(300, 100);
        dialog.setLocationRelativeTo(this);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setVisible(true);
        
        return dialog;
    }
    
    /**
     * 检查注册是否成功
     * @return 如果注册成功返回true，否则返回false
     */
    public boolean isRegistrationSuccess() {
        return registrationSuccess;
    }
    
    /**
     * 显示注册提示对话框
     * @param parent 父窗口
     * @param registrationManager 注册管理器
     * @return 如果用户选择注册并注册成功返回true，否则返回false
     */
    public static boolean showRegistrationPrompt(Frame parent, RegistrationManager registrationManager) {
        // 创建提示对话框
        JDialog promptDialog = new JDialog(parent, "提示", true);
        promptDialog.setSize(300, 150);
        promptDialog.setLocationRelativeTo(parent);
        promptDialog.setResizable(false);
        promptDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        
        // 设置对话框为圆角
        promptDialog.addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override
            public void componentResized(java.awt.event.ComponentEvent e) {
                promptDialog.setShape(new java.awt.geom.RoundRectangle2D.Double(
                    0, 0, promptDialog.getWidth(), promptDialog.getHeight(), 15, 15));
            }
        });
        
        RoundedPanel panel = new RoundedPanel(new BorderLayout(), 15);
        panel.setBorder(BorderFactory.createCompoundBorder(
            new RoundedBorder(Color.LIGHT_GRAY, 10),
            new EmptyBorder(10, 10, 10, 10)
        ));
        
        JLabel messageLabel = new JLabel("您还未注册,请先快速注册");
        messageLabel.setHorizontalAlignment(JLabel.CENTER);
        panel.add(messageLabel, BorderLayout.CENTER);
        
        RoundedPanel buttonPanel = new RoundedPanel(new FlowLayout(FlowLayout.CENTER), 10);
        buttonPanel.setBackground(new Color(240, 240, 240));
        JButton registerButton = new JButton("注册");
        JButton closeButton = new JButton("关闭");
        JButton browseButton = new JButton("浏览");
        
        final boolean[] result = {false};
        
        registerButton.addActionListener(e -> {
            promptDialog.dispose();
            RegistrationDialog registrationDialog = new RegistrationDialog(parent, registrationManager);
            registrationDialog.setVisible(true);
            result[0] = registrationDialog.isRegistrationSuccess();
        });
        
        closeButton.addActionListener(e -> {
            promptDialog.dispose();
        });
        
        browseButton.addActionListener(e -> {
            // 这里可以实现浏览功能，例如打开一个简单的浏览界面
            JOptionPane.showMessageDialog(promptDialog, "浏览功能暂未实现", "提示", JOptionPane.INFORMATION_MESSAGE);
        });
//
//        buttonPanel.add(registerButton);
//        buttonPanel.add(closeButton);
//        buttonPanel.add(browseButton);
//
//        panel.add(buttonPanel, BorderLayout.SOUTH);
        promptDialog.setContentPane(panel);
        promptDialog.setVisible(true);
        
        return result[0];
    }
}